import {Inject, Injectable, OnDestroy, Renderer2} from '@angular/core';
import {Observable, Subject, Subscription} from 'rxjs';
import {EventManager} from '@angular/platform-browser';
import {debounceTime} from 'rxjs/operators';
import {DOCUMENT} from '@angular/common';

@Injectable({
  providedIn: 'root'
})
export class AdaptiveScreenService implements OnDestroy {
  private resizeSubscription: Subscription;
  renderer: Renderer2;
  get onResize$(): Observable<UIEvent> {
    return this.resizeSubject.asObservable();
  }

  private resizeSubject: Subject<UIEvent>;

  constructor(private eventManager: EventManager, @Inject(DOCUMENT) private document) {
    this.resizeSubject = new Subject();
    this.eventManager.addGlobalEventListener('window', 'resize', this.onResize.bind(this));
  }

  private onResize(event: UIEvent) {
    this.resizeSubject.next(event);
  }
  subscribe() {
    this.resizeSubscription = this.onResize$.pipe(debounceTime(300)).subscribe(this.scale.bind(this));
  }

  scale() {
    const ratioX = window.innerWidth / 1920;
    const ratioY = window.innerHeight / 1080;
    this.renderer.setStyle(this.document.body, 'transform', 'scale(' + ratioX + ',' + ratioY + ')');
    this.renderer.setStyle(this.document.body, 'transform-origin', 'left top');
  }

  ngOnDestroy() {
    if (this.resizeSubscription) {
      this.resizeSubscription.unsubscribe();
    }
  }
}
